/*
Skyler Sell
CSCD 330 Spring 2007
HW 1

Server program that accepts connections, then takes strings from the client
and sends them back.  If the string "bye" is sent by the client,
the connection is terminated.
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <fcntl.h>
#define PORT 8082

int main(int argc, char *argv[])
{
	char fromClient[BUFSIZ], toClient[BUFSIZ];
	/* char header[] = "HTTP/1.1 200 OK\n\n"; */
	char *file;
	/* char ch; */

	struct sockaddr_in serv_addr, client_addr;
	int sockfd, len, client_sockfd;
	FILE *fp;

	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
		exit(2);

	memset(&serv_addr, 0, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(PORT);
	serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);

	bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
	listen(sockfd, 2);

	len = sizeof(client_addr);
	for (;;)
	{
		/* printf("Waiting for connection...\n"); */
		while (1)
		{
			client_sockfd = accept(sockfd, (struct sockaddr *)&client_addr, (socklen_t *)&len);
			/* printf("Waiting for message...\n"); */
			read(client_sockfd, fromClient, sizeof(fromClient));
			printf("From client: %s", fromClient);
			if (strncmp(fromClient, "GET / HTTP/1.1\n", strlen("GET")) == 0)
			{
				strtok(fromClient, " "); /* grab GET */
				file = strtok('\0', " ");
				printf("File to be opened: \'%s\'\n", file);
				if (strncmp(file, "/", strlen(file)) == 0)
					fp = fopen("index.html", "r");
				else
					fp = fopen(file+1, "r"); /* advance fp past the leading / and open file */
				/* write(client_sockfd, header, strlen(header)); */
				
				if (fp == NULL)
				{
					fp = fopen("404.html", "r");
				}

				memset(toClient, 0, sizeof(toClient));
				while (fgets(toClient, sizeof(toClient), fp))
				{
					write(client_sockfd, toClient, strlen(toClient));
					memset(toClient, 0, sizeof(toClient));
				}
				puts("zeroing");
				memset(fromClient, 0, sizeof(fromClient));
				fclose(fp);
			}
			else puts("Bad input");
			close(client_sockfd);
			puts("Disconnected client");
		}
		/* write(client_sockfd, quit, strlen(quit)); */
	}
	return 0;
}
